from django.contrib.auth.backends import ModelBackend
import re
from users.models import User

class UserUtils(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        if request is None:

            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            # 判断密码
            if user.check_password(password):
                return user
        else:

            # 判断是手机号还是用户名
            try:
                if re.match(r'1[3-9]\d{9}',username):
                    user = User.objects.get(mobile=username)

                else:
                    user = User.objects.get(username=username)

            except:
                user = None

            if user is not None and user.check_password(password):
                return user